package com.zqw.service.impl;

import com.zqw.info.AdminInfo;
import com.zqw.mapper.AdminMapper;
import com.zqw.pojo.AdminPojo;
import com.zqw.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;

    /**
     * 管理员登录
     * @param admin
     * @return
     */
    public AdminPojo adminLogin(AdminInfo admin){
        AdminPojo adminPojo = adminMapper.adminLogin(admin);
        return adminPojo;
    }

    /**
     * 查询所有的用户
     * @return
     */
    @Override
    public List<AdminPojo> adminList(AdminInfo admin) {
        List<AdminPojo> adminPojos = adminMapper.adminList(admin);
        return adminPojos;
    }

    /**
     * 删除单个用户
     * @param id 要删除的id
     * @return
     */
    @Override
    public boolean delOneAdmin(String id) {
        boolean b = adminMapper.delAdmin(id);
        return b;
    }

    /**
     * 删除多个用户
     * @param ids 要删除的ids
     * @return
     */
    @Override
    public boolean delAdmins(String ids) {
        boolean b = adminMapper.delAdmin(ids.substring(0, ids.length() - 1));
        return b;
    }

    /**
     * 添加用户
     * @param adminInfo
     * @return
     */
    public boolean addAdmin(AdminInfo adminInfo){
        boolean b = adminMapper.addAdmin(adminInfo);
        if(b){
            for (int i = 0; i < adminInfo.getRoles().length; i++) {
                adminMapper.addRoleAdmin(adminInfo.getAid(),adminInfo.getRoles()[i]);
            }
        }
        return b;
    }

    /**
     * 修改用户信息
     * @param adminInfo
     * @return
     */
    @Override
    public boolean updAdmin(AdminInfo adminInfo) throws Exception {
        boolean b = adminMapper.updAdmin(adminInfo);
        if(!b){
            throw new Exception("修改用户失败");
        }
        //是否需要从新绑定角色
        if(adminInfo.getRoles()!=null){
            //删除所有角色
            adminMapper.delRoleAdmin(adminInfo.getAid());
            //绑定新角色
            for (int i = 0; i < adminInfo.getRoles().length; i++) {
                b = adminMapper.addRoleAdmin(adminInfo.getAid(), adminInfo.getRoles()[i]);
                if(!b){
                    throw new Exception("修改用户角色失败");
                }
            }
        }
        return true;
    }

    @Override
    public boolean updAdminStatus(AdminInfo adminInfo) {
        boolean b = adminMapper.updAdmin(adminInfo);
        return b;
    }

    //唯一校验
    public boolean soleAdmin(AdminInfo adminInfo){
        List<AdminPojo> adminPojos = adminMapper.soleAdmin(adminInfo);
        return adminPojos !=null && adminPojos.size()>0;
    }

}
